#include "Queue.h"

void QueueInit(Queue* pq)
{
	assert(pq != NULL);
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}

void QueueDestroy(Queue* pq)
{
	assert(pq != NULL);
	QueueNode* cur = pq->phead;
	while (cur)
	{
		QueueNode* tmp = cur->next;
		free(cur);
		cur = tmp;
	}
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}

QueueNode* QBuyNode(QDataType x)
{
	QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newNode == NULL) {
		perror("malloc fail");
		exit(1);
	}
	newNode->data = x;
	newNode->next = NULL;
	return newNode;
}

void QueuePush(Queue* pq, QDataType x)
{
	assert(pq != NULL);
	QueueNode* newNode = QBuyNode(x);
	if (pq->phead == NULL) {
		pq->phead = newNode;
		pq->ptail = newNode;
	}
	else {
		pq->ptail->next = newNode;
		pq->ptail = pq->ptail->next;
	}
	++pq->size;
}

bool QueueEmpty(Queue* pq)
{
	assert(pq != NULL);
	//return pq->phead == NULL;
	return pq->size == 0;
}

int QueueSize(Queue* pq)
{
	assert(pq != NULL);
	//QueueNode* pcur = pq->phead;
	//int size = 0;
	//while (pcur)
	//{
	//	pcur = pcur->next;
	//	++size;
	//}
	return pq->size;
}

void QueuePop(Queue* pq)
{
	assert(!QueueEmpty(pq));
	if (pq->phead == pq->ptail)
	{
		free(pq->phead);
		pq->phead = NULL;
		pq->ptail = NULL;
	}
	else {
		QueueNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
	--pq->size;
}

QDataType QueueFront(Queue* pq)
{
	assert(!QueueEmpty(pq));
	return pq->phead->data;
}

QDataType QueueBack(Queue* pq)
{
	assert(!QueueEmpty(pq));
	return pq->ptail->data;
}

